package com.eqs.enterprisequestionnaire.service;

import com.eqs.enterprisequestionnaire.model.pojo.Question;
import com.eqs.enterprisequestionnaire.model.pojo.Option;
import com.eqs.enterprisequestionnaire.model.pojo.Answer;
import com.eqs.enterprisequestionnaire.model.pojo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.eqs.enterprisequestionnaire.model.enums.QuestionEnum.isLevelType;
import static com.eqs.enterprisequestionnaire.model.enums.QuestionEnum.isTextType;
import static com.eqs.enterprisequestionnaire.model.enums.QuestionEnum.isChoiceType;
import static com.eqs.enterprisequestionnaire.model.enums.QuestionEnum.isSortType;
@Service
public class CrossAnalysisService {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private OptionService optionService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private ResponseService responseService;

    @Autowired
    private HistoryService historyService;
    public Map<String, Map<String, Double>> crossAnalyze(Integer xQuestionId, Integer yQuestionId) {
        // 获取问题
        Question xQuestion = questionService.getById(xQuestionId);
        Question yQuestion = questionService.getById(yQuestionId);

        // 验证是否属于同一问卷
        if (!xQuestion.getQuestionnaireId().equals(yQuestion.getQuestionnaireId())) {
            throw new IllegalArgumentException("Questions must belong to the same questionnaire.");
        }

        // 验证问题类型
        if (isTextType(xQuestion.getType()) || isSortType(xQuestion.getType()) ||
                isTextType(yQuestion.getType()) || isSortType(yQuestion.getType())) {
            throw new IllegalArgumentException("Text and Sort type questions are not allowed.");
        }

        // 获取X变量的取值
        List<String> xValues = getQuestionValues(xQuestion);
        // 获取Y变量的取值
        List<String> yValues = getQuestionValues(yQuestion);

        // 获取响应
        List<Response> responses = historyService.getListResponseByQuestionnaireId(xQuestion.getQuestionnaireId());

        // 构建结果数据结构
        Map<String, Map<String, Double>> result = new LinkedHashMap<>();

        // 遍历X变量的每个取值
        for (String xValue : xValues) {
            Map<String, Double> yDistribution = new LinkedHashMap<>();
            for (String yValue : yValues) {
                yDistribution.put(yValue, 0.0);
            }
            result.put(xValue, yDistribution);
        }

        // 遍历所有响应
        for (Response response : responses) {
            // 获取该响应下的所有答案
            List<Answer> answers = historyService.getListAnswerByResponseId(response.getId());

            // 过滤出对应X变量和Y变量的答案
            Answer xAnswer = answers.stream()
                    .filter(a -> a.getQuestionId().equals(xQuestionId))
                    .findFirst()
                    .orElse(null);
            Answer yAnswer = answers.stream()
                    .filter(a -> a.getQuestionId().equals(yQuestionId))
                    .findFirst()
                    .orElse(null);

            // 如果存在有效的答案，进行统计
            if (xAnswer != null && yAnswer != null) {
                String xValue = getAnswerValue(xAnswer, xQuestion.getType());
                String yValue = getAnswerValue(yAnswer, yQuestion.getType());
                if (result.containsKey(xValue) && result.get(xValue).containsKey(yValue)) {
                    result.get(xValue).put(yValue, result.get(xValue).get(yValue) + 1);
                }
            }
        }

        // 计算百分比
        for (String xValue : result.keySet()) {
            Map<String, Double> yDistribution = result.get(xValue);
            double total = yDistribution.values().stream().mapToDouble(Double::doubleValue).sum();
            if (total > 0) {
                for (String yValue : yDistribution.keySet()) {
                    yDistribution.put(yValue, yDistribution.get(yValue) / total);
                }
            }
        }

        return result;
    }

    private List<String> getQuestionValues(Question question) {
        if (isChoiceType(question.getType())) {
            return historyService.getListOptionByQuestionId(question.getId())
                    .stream()
                    .map(Option::getContent)
                    .collect(Collectors.toList());
        } else if (isLevelType(question.getType())) {
            return Arrays.asList("1", "2", "3", "4", "5");
        }
        return Collections.emptyList();
    }

    private String getAnswerValue(Answer answer, String questionType) {
        if (isChoiceType(questionType)) {
            return optionService.getById(Integer.parseInt(answer.getContent())).getContent();
        } else if (isLevelType(questionType)) {
            return answer.getText();
        }
        return "";
    }
}